#!/usr/bin/python
# -*- coding:utf-8 -*-

import configparser
import os
import json

relate_read_file_path = r"tdx_config\connect.cfg"
relate_write_file_path = r"tdx_config\tdx_trader_server_cfg.json"

# 用os模块来读取
current_path = os.path.dirname(os.path.realpath(__file__))
cfg_path = os.path.join(current_path, relate_read_file_path)  # 读取到本机的配置文件

# 调用读取配置模块中的类
conf = configparser.ConfigParser()
conf.read(cfg_path)

print(conf.sections())
target_section_name = 'HQHOST'
if conf.has_section(target_section_name):
    print('find section', target_section_name, '.')
    hq_host = conf[target_section_name]
    HostNum = int(hq_host['HostNum'])
    print('HostNum =', HostNum)
    elem_array = []
    for i in range(1, HostNum + 1):
        key_hostname = 'HostName%02d' % (i)
        key_IPAddress = 'IPAddress%02d' % (i)
        key_Port = 'Port%02d' % (i)
        value_hostname = hq_host[key_hostname]
        value_IPAddress = hq_host[key_IPAddress]
        value_port = hq_host[key_Port]
        print(i, key_hostname, key_IPAddress, key_Port)
        print(value_hostname, value_IPAddress, value_port)
        elem = {'server_addr': value_IPAddress,
                'server_port': value_port,
                'server_name': value_hostname,
                'index': i}
        elem_array.append(elem)
    # 然后写入 tdx_trader_server_cfg.json 文件
    with open(relate_write_file_path, mode='w') as file_object:
        json_top = {'server_config': elem_array}
        json.dump(json_top, file_object, indent=4)
